package com.songlanyun.modules.rabbitmq.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.rabbitmq.DelayedConstant;
import com.songlanyun.modules.rabbitmq.MqConstant;
import com.songlanyun.modules.rabbitmq.config.RabbitConfig;
import com.songlanyun.modules.rabbitmq.entity.MsgLog;
import com.songlanyun.modules.rabbitmq.mapper.MsgLogMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class SendMsgService {

    public static final String COMMON_MSG_MARK_CODE = "common";
    @Resource
    private MsgLogMapper msgLogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MsgLogService msgLogService;

    /**
     * 直接对
     *
     * @param jsonStr
     * @return
     */
    public R send(String jsonStr) {
        //String msgId = RandomUtil.simpleUUID();
        String msgId = IdUtil.simpleUUID();

        //请求头设置消息id（messageId）
        Message message = MessageBuilder.withBody(jsonStr.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(msgId).build();

        MsgLog msgLog = new MsgLog(msgId, jsonStr, MqConstant.PROCEEDS_EXCHANGE, MqConstant.PROCEEDS_ROUTER);
        msgLogMapper.insert(msgLog);// 消息入库

        CorrelationData correlationData = new CorrelationData(msgId);
        rabbitTemplate.convertAndSend(MqConstant.PROCEEDS_EXCHANGE, MqConstant.PROCEEDS_ROUTER, message, correlationData);// 发送消息

        return R.ok("消息发送成功");
    }

    /**
     * 根据 exange,routingKey 发送消息
     *
     * @param exchange
     * @param routingKey
     * @param jsonStr
     * @return
     */
    public R send(String exchange, String routingKey, String jsonStr) {
        String msgId;
//        msgId = RandomUtil.simpleUUID();
        msgId = IdUtil.simpleUUID();

        //请求头设置消息id（messageId）
        Message message = MessageBuilder.withBody(jsonStr.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(msgId).build();


        msgLogService.saveMsgLog(msgId, MqConstant.MsgLogStatus.DELIVERING, exchange, routingKey, jsonStr);

        CorrelationData correlationData = new CorrelationData(msgId);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);// 发送消息

        return R.ok("消息发送成功");
    }

    /**
     * 根据 exange,rotingkey 发送普通及时消息  -- 不保存msg_log
     *
     * @param exchange
     * @param routingKey
     * @param jsonStr
     */
    public R sendCommon(String exchange, String routingKey, String jsonStr) {

        //请求头设置消息id（messageId）
        Message message = MessageBuilder.withBody(jsonStr.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(COMMON_MSG_MARK_CODE).build();

        CorrelationData correlationData = new CorrelationData(COMMON_MSG_MARK_CODE);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);// 发送消息

        return R.ok("消息发送成功");
    }


    /**
     * 发送延迟消息
     *
     * @param exchange   交换机名
     * @param routingKey 路由
     * @param jsonStr    内容
     * @param delaySec   延迟秒数
     */
    public R send(String exchange, String routingKey, String jsonStr, int delaySec) {
        // String msgId = RandomUtil.simpleUUID();
        String msgId = IdUtil.simpleUUID();
        //请求头设置消息id（messageId）
        Message message = MessageBuilder.withBody(jsonStr.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(msgId).build();

        msgLogService.saveMsgLog(msgId, MqConstant.MsgLogStatus.DELIVERING, exchange, routingKey, jsonStr);

        CorrelationData correlationData = new CorrelationData(msgId);

        rabbitTemplate.convertAndSend(exchange, routingKey, message, a -> {
            a.getMessageProperties().setDelay(delaySec * 1000);
            return a;
        }, correlationData);
        return R.ok("消息发送成功");


        /**
         public void sendMsg(String queueName,String msg) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         System.out.println("消息发送时间:"+sdf.format(new Date()));
         rabbitTemplate.convertAndSend("test_exchange", queueName, msg, new MessagePostProcessor() {
        @Override public Message postProcessMessage(Message message) throws AmqpException {
        message.getMessageProperties().setHeader("x-delay",3000);
        return message;
        }
        });
         }
         **/


    }


}

